﻿#region

using Vin.Extension.Framework.Login.Entities;
using Vin.Extension.Framework.Login.Repository;
using Vin.Extension.Framework.Login.ServiceInterface;
using Vin.Tool.AspNetCore.Service;
using Vin.Tool.Attributes;

#endregion

namespace Vin.Extension.Framework.Login.Service;

public class SysAccountService : VinBaseService, ISysAccountService
{
    [Inject] private readonly ISysPasswordService _sysPasswordService = null!;
    
    [Inject] private readonly SysAccountRepository _sysAccountRepository = null!;

    public async Task<SysAccount> QueryByIdAsync(long? id)
    {
        return await _sysAccountRepository.GetByIdAsync(id);
    }

    public async Task<SysAccount?> QueryByAccountAsync(string account)
    {
        return await _sysAccountRepository.QueryByAccountAsync(account);
    }

    /// <summary>
    /// 查询或添加账号
    /// </summary>
    public async Task<(long?, bool)> QueryOrAddAsync(string account, string password)
    {
        var res = await _sysAccountRepository.QueryIdByAccount(account);
        if (res.HasValue)
        {
            return (res, false);
        }
        
        password = _sysPasswordService.Encrypt(password);
        return (await _sysAccountRepository.CreateAccount(account, password), true);
    }

    public async Task<bool> CheckAccountExistsAsync(string account)
    {
        return await _sysAccountRepository.CheckAccountExistsAsync(account);
    }

    public async Task<bool> ResetPasswordAsync(long? id, string password)
    {
        password = _sysPasswordService.Encrypt(password);
        return await _sysAccountRepository.UpdateAccountAsync(new SysAccount()
        {
            Id = id,
            Password = password
        });
    }

    public async Task<bool> DelAsync(long id)
    {
        return await _sysAccountRepository.LogicDeleteAsync(m => m.Id == id);
    }

    public async Task<bool> ChangeEnabledAsync(long id, bool? enabled)
    {
        if (!enabled.HasValue) return false;
        return await _sysAccountRepository.UpdateAccountAsync(new SysAccount()
        {
            Id = id,
            IsEnabled = enabled,
        });
    }
}